package hn.cch.listener;

import hn.cch.entity.Order;
import hn.cch.entity.User;
import hn.cch.service.UserService;
import hn.cch.util.JsonUtil;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@RocketMQMessageListener(consumerGroup = "shop-user", topic = "order-topic",
        consumeMode = ConsumeMode.CONCURRENTLY,//消费模式:无序和有序
        messageModel = MessageModel.CLUSTERING//消息模式:广播和集群,默认是集群
)
public class OrderListener implements RocketMQListener<Order> {

    private static Logger logger = LoggerFactory.getLogger(OrderListener.class);

    @Autowired
    private UserService userService;


    @Override
    public void onMessage(Order order) {
        logger.info("RocketMQ Message Listener order:{}", JsonUtil.toJsonString(order));

        //下单成功之后使用消息队列通知用户模块扣除余额
        User user = userService.findById(order.getUserId());
        double temp = user.getUserBalances() - order.getBuyMoney();
        if (temp >= 0){
            user.setUserBalances(temp);
            userService.save(user);
            logger.info("用户扣款成功");
        } else {
            logger.error("用户余额不足");
        }



    }
}
